package com.ruoyi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class CopyExcelWithStyles {
    public static void main(String[] args) throws IOException {
        String sourceFilePath = "d:\\code\\分支机构信息表-填报说明.xlsx";
        String destinationFilePath = "d:\\code\\分支机构信息表-填报说明1.xlsx";

        try (InputStream is = new FileInputStream(sourceFilePath);
             Workbook workbook = new XSSFWorkbook(is);
             FileOutputStream fos = new FileOutputStream(destinationFilePath);) {

            Workbook newWorkbook = new XSSFWorkbook();
            CreationHelper createHelper = newWorkbook.getCreationHelper();

            // 复制每个sheet
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                Sheet newSheet = newWorkbook.createSheet(sheet.getSheetName());

                // 复制每行
                for (Row row : sheet) {
                    Row newRow = newSheet.createRow(row.getRowNum());

                    // 复制每个单元格
                    for (Cell cell : row) {
                        Cell newCell = newRow.createCell(cell.getColumnIndex());
                        newCell.setCellStyle(cell.getCellStyle()); // 保留样式
                        switch (cell.getCellType()) {
                            case STRING:
                                newCell.setCellValue(cell.getStringCellValue());
                                break;
                            case NUMERIC:
                                newCell.setCellValue(cell.getNumericCellValue());
                                break;
                            case BOOLEAN:
                                newCell.setCellValue(cell.getBooleanCellValue());
                                break;
                            case FORMULA:
                                newCell.setCellFormula(cell.getCellFormula());
                                break;
                            default:
                                break;
                        }
                    }
                }
            }

            // 写入新文件
            newWorkbook.write(fos);
        }

        System.out.println("Excel with styles copied successfully.");
    }
}
